import { useEffect, useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'

import { getCityList, getHotCity, getCity } from '../../api/request';
import getlocaltion from '../../utils/getlocaltion';

import { NavBar, Space, SpinLoading } from 'antd-mobile';
import { List, AutoSizer } from "react-virtualized";

import './index.scss';
const INDEX_HEIGHT = 36;
const NAME_HEIGHT = 50;

export default function CityList() {

  const [cityList, setcityList] = useState({});
  const [cityIndex, setcityIndex] = useState([]);
  const [activeIndex, setactiveIndex] = useState(0);
  const [isLoading, setisLoading] = useState(true);

  const listref = useRef(null);

  useEffect(() => {
    if (cityIndex.length == 0) {
      get_city_list();
    } else {
      listref.current.measureAllRows();
    }
  }, [cityList]);

  //获取城市列表 --- 处理数据
  let get_city_list = async () => {
    const city_list = {};
    // const city_index = [];
    let citylist = await getCityList();
    let hotcity = await getHotCity();

    // 获取当前城市信息
    let localtionCity = await getlocaltion();
    console.log(localtionCity);
    citylist.data.body.forEach(item => {
      // 获取每个城市的首字母
      const first = item.short.substr(0, 1);
      if (city_list[first]) {
        // 如果有
        city_list[first].push(item);
      } else {
        city_list[first] = [item];
      }
    });
    const city_index = Object.keys(city_list).sort();

    //  添加热门城市进去
    city_list.hot = hotcity.data.body;
    city_index.unshift('hot');

    // 添加当前城市信息
    city_list['#'] = [localtionCity];
    city_index.unshift('#');
    setcityList(city_list);
    setcityIndex(city_index);
    setisLoading(false);
  }

  // 切换索引字母
  const changeActive = (index) => {
    setactiveIndex(index);
    listref.current.scrollToRow(index)
  }
  const navigate = useNavigate();
  //返回键
  const back = () => {
    navigate(-1);
  }

  // 切换城市
  const changeCity = async (name) => {
    const res = await getCity(name);
    console.log(res);
    //  存信息到缓存，返回上一页
    localStorage.setItem('city', JSON.stringify(res.data.body));
    back();
  }

  // 计算每个字开头的城市
  const city_arr = (letter) => {
    return cityList[letter]
  }

  // 计算每行的高度
  const getRowHight = ({ index }) => {
    return INDEX_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT
  }

  // 渲染每一行的内容
  function rowRenderer({
    key,         // Unique key within array of rows
    index,       // 索引号
    isScrolling, // 当前项是否正在滚动中
    isVisible,   // 当前项在List中是可见的
    style        // 重点属性：一定要给每一个行数添加该样式
  }) {
    let city_key = cityIndex[index];

    return (
      <div
        key={key}
        style={style}
        className='city_item'
      >
        <div className='city_item_title'>{cityIndex[index] == "#" ? '当前城市' : cityIndex[index] == "hot" ? '热门城市' : cityIndex[index].toUpperCase()}</div>
        {
          city_arr(city_key).map((item) =>
          (<div className='city_item_name' onClick={() => {
            changeCity(item.label)
          }} key={item.label}>{item.label}</div>)
          )
        }

      </div>
    )
  }

  return (
    <div className='City_box'>
      <NavBar back='返回' onBack={back} className='navbar'>
        城市列表
      </NavBar>

      {/* 圈圈列表 */}
      
      {isLoading && (<div className='loading'>
        <Space direction='horizontal' wrap block style={{ '--gap': '16px' }}>
          <SpinLoading style={{ '--size': '120px' }} />
        </Space>
        <span className='loading_title'>数据加载中。。。</span>
      </div>)}
      {/* 列表 */}
      <AutoSizer>
        {
          ({ width, height }) => (
            <List
              ref={listref}
              // 组件的宽度
              width={width}
              // 组件的高度
              height={height}
              rowCount={cityIndex.length}
              // 每行的高度
              rowHeight={getRowHight}
              rowRenderer={rowRenderer}
              scrollToAlignment="start"
            />
          )
        }
      </AutoSizer>
      {/* 侧边栏字母 */}
      <div className='aside_letter'>
        {
          cityIndex.map((item, index) =>
          (<div className={index == activeIndex ? 'aside_letter_item active' : 'aside_letter_item'} key={index} onClick={() => { changeActive(index) }}>
            {item == 'hot' ? '热' : item}
          </div>)
          )
        }
      </div>
    </div>
  )
}
